/*
 * Copyright (C) 2010 by Lei Shi (sjtushi@gmail.com)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License, 
 * version 2, or any later versions.
 *
 */

#include "proc.h"

int main (int argc, char **argv)
{
   xa_instance_t xai;
   proc_t proc;
   unsigned char *memory = NULL;

   uint32_t offset, task_addr, list_head;

   if (argc != 2) {
      printf("Usage: xen-ps <domid>\n");
      printf("       xen-ps report a snapshot of current processes in domain <domid>\n");
      return STATUS_ERROR;
   }

   proc.domid = atoi(argv[1]);

   if (init_xa_instance(&xai, proc.domid) != STATUS_SUCCESS){
      return STATUS_ERROR;
   }

   memory = 
      xa_access_kernel_sym(&xai, "init_task", &offset, PROT_READ);
   CHECK_MAPPED_MEMORY(memory);
   memcpy(&list_head, 
	 memory + offset + TASKSTRUCT_TASKS_OFFSET, 4);

   task_addr = list_head;
   munmap(memory, xai.page_size);
   printf("PID   COMMAND\n");

   while(1) {
      memory = 
	 xa_access_kernel_va(&xai, task_addr, &offset, PROT_READ);
      CHECK_MAPPED_MEMORY(memory);
      memcpy(&task_addr, memory + offset, 4);

      if (task_addr == list_head)
	 break;

      if (getproc_from_guest((addr_t)(memory + offset), &proc) 
	    != STATUS_SUCCESS) {
	 return STATUS_ERROR;
      }

      print_proc(&proc, PRINT_PROC_PS_MODE);
      munmap(memory, xai.page_size);

   }

   if (memory != NULL)
      munmap(memory, xai.page_size);

   return 0;
}
